/** * 运营管理-活动管理 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">运营管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search" align="left">
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">新增</el-button>
        <el-button size="small" type="danger" @click="batchDel()">批量删除</el-button>
      </el-form-item>
      <el-form-item label="搜索:">
        <el-input size="small" v-model="formInline.title" placeholder="活动标题" class="searchInput"/>
        <el-select size="small" v-model="formInline.active" placeholder="是否上架" class="searchSelect">
            <el-option label="已上架" value="2"/>
            <el-option label="未上架" value="1"/>
        </el-select>
        <el-select size="small" v-model="formInline.status" placeholder="活动状态" class="searchSelect">
            <el-option label="未开始" value="未开始"/>
            <el-option label="进行中" value="进行中"/>
            <el-option label="已完成" value="已完成"/>
        </el-select>
        <el-date-picker v-model="searchTime" type="datetimerange" value-format="yyyy-MM-dd hh:mm:ss" 
        range-separator="-" start-placeholder="开始日期" end-placeholder="截止日期" class="timePicker"/>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="getdata()">搜索</el-button>
        <el-button size="small" type="danger" @click="clearConditon()">重置</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="listData" highlight-current-row border :row-key="getRowKeys" ref="multipleSelectable"
    @selection-change="handleSelectionChange" style="width: 100%" @sort-change="sortChange">
      <el-table-column align="center" type="selection" width="40" :reserve-selection="true"/>
      <el-table-column align="center" prop="id" label="序号" width="50"/>
      <el-table-column align="center" prop="title" label="活动标题" width="100"/>
      <el-table-column align="center" prop="description" label="活动介绍" width="150"/>
      <el-table-column align="center" prop="poster" label="活动海报" width="150">
        <template slot-scope="scope">
          <img :src="scope.row.poster"  min-width="70" height="70" />
        </template>
      </el-table-column>
      <el-table-column align="center" prop="link" label="活动链接" width="150">
        <template slot-scope="scope">
          <a :href="scope.row.link" target="_blank" style="text-decoration:none">{{scope.row.link}}</a>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="startTime" label="开始时间" width="150" sortable="custom"/>
      <el-table-column align="center" prop="endTime" label="结束时间" width="150" sortable="custom"/>
      <el-table-column align="center" prop="active" label="是否上架" width="80">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.active=='2'?nshow:fshow" @change="editEnable(scope.row)" active-color="#13ce66" inactive-color="#ff4949"/>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="status" label="活动状态" width="80"/>
      <el-table-column align="center" label="操作" min-width="350">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="showCoupon(scope.row)">优惠券</el-button>
            <el-button size="mini" type="success" @click="showMessage(scope.row)">发消息</el-button>
            <el-button size="mini" type="warning" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="deleteOne(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination :child-msg="pageparm" @callFather="callFather" align="center"/>
    <!-- 新增、编辑页面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="60%" :before-close="closeDialog">
      <el-form :inline="true" label-width="100px" :model="editForm" ref="editForm" :rules="rules">
        <el-form-item label="活动标题" prop="title" >
          <el-input size="small" v-model="editForm.title"/>
        </el-form-item>
        <el-form-item label="活动时间">
          <el-date-picker v-model="editTime" type="datetimerange" value-format="yyyy-MM-dd hh:mm:ss"
        range-separator="-" start-placeholder="开始日期" end-placeholder="截止日期" class="timePicker"/>
        </el-form-item>
        <el-form-item label="活动链接" prop="link" >
          <el-input size="small" v-model="editForm.link"/>
        </el-form-item>
        <el-form-item label="活动状态" prop="status">
          <el-select size="small" v-model="editForm.status" placeholder="活动状态" class="mySelect">
            <el-option label="未开始" value="未开始"/>
            <el-option label="进行中" value="进行中"/>
            <el-option label="已结束" value="已结束"/>
          </el-select>
        </el-form-item>
        <el-form-item label="活动海报" prop="poster" >
          <el-upload class="avatar-uploader" action="http://192.168.8.108:12306/aliyunoss/file/upload" accept=".jpeg,.png,.jpg,.bmp,.gif"
            :show-file-list="false" :on-success="uploadSuccess" :before-upload="beforeUpload" :headers="headers">
            <img v-if="editForm.poster" :src="editForm.poster" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="活动介绍" prop="description">
          <el-input type="textarea" v-model="editForm.description" style="width:300px;" :rows="5"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button size="small" @click="cancelDialog">取消</el-button>
        <el-button size="small" type="primary" class="title"
          @click="submitForm()">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "../Pagination";
export default {
  data() {
    return {
      nshow: true, //switch开启
      fshow: false, //switch关闭
      // 控制编辑页面显示与隐藏
      editFormVisible: false, 
      // 新增、编辑页面的标题
      title: "新增活动",
      // 编辑页面数据
      editForm: {
        id: "",
        title: "",
        poster: "",
        link: "",
        active: "",
        status: "",
        description: "",
        startTime: "",
        endTime: "",
        userId: "",
      },
      // 验证规则
      rules: {
        title: [
          {required: true,message: '请输入活动标题', trigger: 'blur'},
        ],
        status: [
          {required: true,message: '请选择活动状态', trigger: 'blur'},
        ],
      },
      // 搜索框时间
      searchTime:["",""],
      // 编辑框时间
      editTime:["",""],
      // 搜索框数据
      formInline: {
        title: "",
        active: "",
        status: "",
        startTime:"",
        endTime:"",
      },
      // 表单数据
      listData: [], 
      // 表单选择数组
      multipleSelection: [],
      // 初始化分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 5,
        total: 0,
      },
      // 时间插件
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < new Date(this.editForm.startTime);
        },
      },
      // 排序字段
      orderSort:"",
      orderKey:"",
    };
  },
  // 注册组件
  components: {Pagination},

  //创建完毕
  created() {
    // 获取表单数据
    this.getdata();
  },
  computed: {
  headers() {// 获取token
    return{
      "authorization": localStorage.getItem('Authorization'),
      "refreshtoken": localStorage.getItem('refreshtoken'),
    }
  },
},
  // 定义方法
  methods: {
    // 清空搜索条件
    clearConditon(){
      this.searchTime=["",""];
      this.formInline.title= "";
      this.formInline.active= "";
      this.formInline.status= "";
      this.getdata();
    },
    // 获取表单数据
    getdata() {
      this.formInline.startTime=this.searchTime[0];
      this.formInline.endTime=this.searchTime[1];
      let queryEntity={
        currentPage:this.pageparm.currentPage,
        pageSize:this.pageparm.pageSize,
        entity:this.formInline,
        orderSort:this.orderSort,
        orderKey:this.orderKey
      };
      this.$axios.post("business/activity/condition",queryEntity)
      .then((res) => {
          if (res.data.code == 200) {
              this.listData = res.data.data.list;
              //对总数量进行赋值
              this.pageparm.total = res.data.data.total;
          }else{
              this.$message({type: 'info',message: res.data.message})
          }
      })
      .catch(err => {
          this.$message.error('数据加载失败，请稍后再试！')
      })
    },
    // 分页插件事件
    callFather(parm) {
      this.pageparm.currentPage = parm.currentPage;
      this.pageparm.pageSize = parm.pageSize;
      this.getdata();
    },
    // 排序方法
    sortChange(column) {
        if (column.order == "ascending") {
          this.orderSort = 'asc'
        } else if (column.order == "descending") {
          this.orderSort = 'desc'
        } else {
          this.orderSort = ''
        }
        this.orderKey=column.prop;
        this.getdata();
      },
    //显示新增、编辑界面
    handleEdit: function (obj) {
      this.editFormVisible = true;
      if (obj != undefined && obj != "undefined") {
        this.title = "编辑活动";
        //填充数据
        this.editForm = obj;
        this.editTime = [obj.startTime,obj.endTime];
      } else {
        this.title = "新增活动";
        //清空数据
        this.editForm.id = "";
        this.editForm.title = "";
        this.editForm.poster = "";
        this.editForm.link = "";
        this.editForm.active = "1";
        this.editForm.status = "";
        this.editForm.description = "";
        this.editForm.startTime = "";
        this.editTime = ["",""];
        this.editForm.userId = "1";
      }
    },
    // 编辑、增加页面保存方法
    submitForm() {
      this.$refs["editForm"].validate((valid) => {
        if (!valid) {
          this.$message.error("请按要求填写表单！");
        }else{
          this.editForm.startTime = this.editTime[0];
          this.editForm.endTime = this.editTime[1];
          // 判断是修改还是新增
          if (this.editForm.id == "") {
            // 新增
            this.$axios.post("business/activity/", this.editForm)
            .then((res) => {
                //关闭弹窗
                this.$refs["editForm"].resetFields();
                this.editFormVisible = false;
                if (res.data.code == 200) {
                    //刷新数据
                    this.getdata();
                    this.$message({
                        type: "success",
                        message: "保存成功！",
                    });
                } else {
                    this.$message({
                        type: "info",
                        message: res.data.message,
                    });
                }
            })
            .catch((err) => {
              this.editFormVisible = false;
              this.$message.error(err.response.data.message);
            });
          } else {
            // 修改
            this.$axios.put("/business/activity/", this.editForm)
            .then((res) => {
                //关闭弹窗
                this.$refs["editForm"].resetFields();
                this.editFormVisible = false;
                if (res.data.code == 200) {
                    //刷新数据
                    this.getdata();
                    this.$message({
                        type: "success",
                        message: "保存成功！",
                    });
                } else {
                    this.$message({
                        type: "info",
                        message: res.data.message,
                    });
                }
            })
            .catch((err) => {
              this.editFormVisible = false;
              this.$message.error("保存失败，请稍后再试！");
            });
          }
        }
      });
    },
    // 删除一个
    deleteOne(obj) {
        this.$confirm("确定要删除吗?", "信息", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
        .then(() => {
            this.$axios.delete("/business/activity/"+obj.id)
            .then((res) => {
              if (res.data.code == 200) {
                this.$message({
                  type: "success",
                  message: "已删除!",
                });
                this.getdata();
              } else {
                this.$message({
                  type: "info",
                  message: res.data.message,
                });
              }
            })
            .catch((err) => {
              this.$message.error("删除失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 批量删除
    batchDel() {
        if(this.multipleSelection.length==0){
            this.$message({
                type: "info",
                message: "请先勾选需要删除的列",
            });
            return;
        }
        this.$confirm("确定要删除吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        })
        .then(() => {
            this.$axios.post("/business/activity/batchDel",this.multipleSelection)
            .then((res) => {
              this.$refs.multipleSelectable.clearSelection();
              if (res.data.code == 200) {
                this.$message({
                  type: "success",
                  message: "已删除!",
                });
                this.getdata();
              } else {
                this.$message({
                  type: "info",
                  message: res.data.message,
                });
              }
            })
            .catch((err) => {
              this.$refs.multipleSelectable.clearSelection();
              this.$message.error(err.response.data.message);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 启用开关
    editEnable(obj) {
      let newObj=obj;
      newObj.active=3-obj.active;
      // 修改
      this.$axios.put("business/activity/", newObj)
      .then((res) => {
          if (res.data.code == 200) {
              //刷新数据
              this.getdata();
              this.$message({
                  type: "success",
                  message: "操作成功！",
              });
          } else {
              this.$message({
                  type: "info",
                  message: res.data.message,
              });
          }
      })
      .catch((err) => {
        this.editFormVisible = false;
        this.$message.error("操作失败，请稍后再试！");
      });
    },
    // 关闭编辑、增加弹出框
    cancelDialog() {
      this.$refs["editForm"].resetFields();
      this.editFormVisible = false;
    },
    // 关闭前清空验证信息
    closeDialog(done){
      this.$refs["editForm"].resetFields();
      done();
    },
    // 处理表单多选
    handleSelectionChange(val) {
        this.multipleSelection=[];
        for(let index in val){
            this.multipleSelection[index]=val[index].id;
        }
    },
    //上传图片的回调
    uploadSuccess(res) {
      this.editForm.poster = res.data.url;
    },
    //上传前的校验
    beforeUpload(file) {
      const fileName = file.name;
      const fileType = fileName.substring(fileName.lastIndexOf('.')).toLowerCase();
      // 检查格式
      if (fileType === '.jpg' || fileType === '.png' || fileType === '.jpeg' || fileType === '.bmp' || fileType === '.gif') {
        // 检查大小
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传图片不能超过2MB!');
          return false;
        }
      } else {
        this.$message.error('请上传正确的图片类型');
        return false;
      }
    },
    //显示优惠券
    showCoupon(obj) {
      this.$router.push({path: '/index/business/coupon',query:{ activityId:obj.id}});
    },
    //发送消息
    showMessage(obj) {
      this.$router.push({path: '/index/business/message',query:{ activityId:obj.id}});
    },
    getRowKeys(row) {
        return row.id;
    },
  },
};
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
.searchInput{
  width: 100px;
}
.timePicker{
  width: 230px;
}
.mySelect{
  width: 193px;
}
.searchSelect{
  width: 100px;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 50px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 193px;
    height: 120px;
    display: block;
  }
</style>
